import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import 'echarts-gl';
import styled from 'styled-components';

const DashboardContainer = styled.div`
  width: 100%;
  height: 100vh;
  background-color: #0a1949;
  color: #fff;
  padding: 20px;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: 25% 50% 25%;
  grid-gap: 20px;
`;

const Panel = styled.div`
  background-color: rgba(6, 30, 93, 0.5);
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
`;

const Header = styled.div`
  font-size: 16px;
  color: #00f2f1;
  margin-bottom: 15px;
  border-left: 4px solid #00f2f1;
  padding-left: 10px;
`;

const ChartContainer = styled.div`
  width: 100%;
  height: 300px;
`;

const TableContainer = styled.div`
  width: 100%;
  height: 300px;
  overflow-y: auto;
  
  table {
    width: 100%;
    border-collapse: collapse;
    
    th, td {
      padding: 10px;
      text-align: left;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    th {
      color: #00f2f1;
    }
  }
`;

const TopHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: rgba(6, 30, 93, 0.7);
  margin-bottom: 20px;
  
  .logo {
    font-size: 24px;
    font-weight: bold;
    color: #00f2f1;
  }
  
  .title {
    font-size: 28px;
    color: #00f2f1;
  }
  
  .time {
    font-size: 20px;
    color: #fff;
  }
`;

interface CircleProgressProps {
  color: string;
  percentage: number;
  children?: React.ReactNode;
}

const CircleProgress = styled.div<CircleProgressProps>`
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: ${props => `conic-gradient(${props.color} ${props.percentage}%, transparent 0)`};
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &::before {
    content: '';
    width: 90px;
    height: 90px;
    background: rgba(6, 30, 93, 0.7);
    border-radius: 50%;
    position: absolute;
  }
  
  .percentage {
    width: 100%;
    position: relative;
    z-index: 1;
    font-size: 24px;
    font-weight: bold;
    color: #fff;
  }
`;

const SemiCircleProgress = styled.div<{color: string; percentage: number}>`
  width: 200px;
  height: 100px;
  position: relative;
  background-color: transparent;
  overflow: hidden;
  
  &::before {
    content: '';
    width: 200px;
    height: 200px;
    position: absolute;
    border-radius: 50%;
    background: ${props => `conic-gradient(${props.color} ${props.percentage * 1.8}deg, rgba(255,255,255,0.1) 0)`};
    top: 0;
    left: 0;
    transform: rotate(-180deg);
  }
  
  .percentage {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 24px;
    font-weight: bold;
    color: ${props => props.color};
  }
  
  .label {
    position: absolute;
    bottom: -5px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 14px;
    color: #fff;
  }
`;

const CityStores: React.FC = () => {
  const pieChartRef = useRef<HTMLDivElement>(null);
  const lineChartRef = useRef<HTMLDivElement>(null);
  const barChartRef = useRef<HTMLDivElement>(null);
  
  // 当前时间
  const [currentTime, setCurrentTime] = React.useState(new Date());

  const list = [ 
    { name: '食品', buyers: 1789, amount: 23695.8 },
    { name: '日用', buyers: 2100, amount: 18900.0 },
    { name: '家电', buyers: 1950, amount: 16575.0 },
    { name: '生鲜', buyers: 2400, amount: 31200.0 },
    // { name: '面包', buyers: 1800, amount: 12600.0 },
    // { name: '巧克力', buyers: 1500, amount: 22500.0 },
    // { name: '坚果', buyers: 1200, amount: 24000.0 },
    // { name: '水果糖', buyers: 1650, amount: 8250.0 },
    // { name: '火腿肠', buyers: 1400, amount: 12600.0 },
    // { name: '方便面', buyers: 2000, amount: 16000.0 }
  ]
  
  useEffect(() => {
    // 更新时间
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    
    // 初始化图表
    if (pieChartRef.current) {
      const chart = echarts.init(pieChartRef.current);
      const option = {
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            startAngle: 90,
            label: {
              show: true,
              formatter: '{b}\n{d}%',
              color: '#fff',
              fontSize: 14,
              position: 'outside'
            },
            labelLine: {
              length: 20,
              length2: 30,
              lineStyle: {
                color: '#fff'
              }
            },
            itemStyle: {
              borderWidth: 8,
              borderColor: '#181f3a',
              shadowBlur: 30,
              shadowColor: 'rgba(0,0,0,0.5)'
            },
            data: [
              { value: 26.2, name: '日用类', itemStyle: { color: '#ff4bec' } },
              { value: 14.3, name: '家电类', itemStyle: { color: '#00f2f1' } },
              { value: 11.3, name: '生鲜类', itemStyle: { color: '#00cfff' } },
              { value: 48.2, name: '食品类', itemStyle: { color: '#7a1dff' } }
            ]
          }
        ],
        backgroundColor: 'transparent'
      };
      chart.setOption(option);
    }

    if (lineChartRef.current) {
      const chart = echarts.init(lineChartRef.current);
      const option = {
        grid: {
          top: 30,
          left: 50,
          right: 20,
          bottom: 30
        },
        legend: {
          data: ['线上销售', '线下门店'],
          textStyle: {
            color: '#fff'
          },
          right: 10,
          top: 0
        },
        xAxis: {
          type: 'category',
          data: ['8:00', '11:00', '14:00', '17:00', '20:00', '22:00'],
          axisLine: {
            lineStyle: { color: '#0066ff' }
          },
          axisLabel: { color: '#fff' }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: { color: '#0066ff' }
          },
          splitLine: {
            lineStyle: { color: 'rgba(255,255,255,0.1)' }
          },
          axisLabel: { color: '#fff' }
        },
        series: [
          {
            name: '线上销售',
            type: 'line',
            smooth: true,
            data: [100, 200, 150, 300, 400, 200],
            itemStyle: { color: '#00f2f1' },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(0,242,241,0.3)' },
                { offset: 1, color: 'rgba(0,242,241,0)' }
              ])
            }
          },
          {
            name: '线下门店',
            type: 'line',
            smooth: true,
            data: [150, 250, 200, 350, 300, 100],
            itemStyle: { color: '#ff4bec' },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255,75,236,0.3)' },
                { offset: 1, color: 'rgba(255,75,236,0)' }
              ])
            }
          }
        ]
      };
      chart.setOption(option);
    }

    if (barChartRef.current) {
      const chart = echarts.init(barChartRef.current);
      const option = {
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        legend: {
          data: ['线下门店', '线上门店'],
          textStyle: {
            color: '#fff'
          },
          right: 10,
          top: 0
        },
        xAxis: {
          type: 'value',
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false }
        },
        yAxis: {
          type: 'category',
          data: ['04-30', '04-25', '04-20', '04-15', '04-10', '04-05', '04-01'],
          axisLine: { lineStyle: { color: '#0066ff' } },
          axisLabel: { color: '#fff' }
        },
        series: [
          {
            name: '线下门店',
            type: 'bar',
            stack: 'total',
            data: [360, 360, 360, 360, 360, 360, 360],
            itemStyle: { color: '#7a1dff' }
          },
          {
            name: '线上门店',
            type: 'bar',
            stack: 'total',
            data: [360, 360, 360, 360, 360, 360, 360],
            itemStyle: { color: '#00f2f1' }
          }
        ]
      };
      chart.setOption(option);
    }

    // 窗口大小变化时重新调整图表大小
    const handleResize = () => {
      [pieChartRef, lineChartRef, barChartRef].forEach(ref => {
        if (ref.current) {
          const chart = echarts.getInstanceByDom(ref.current);
          chart?.resize();
        }
      });
    };
    
    window.addEventListener('resize', handleResize);

    // 清理函数
    return () => {
      clearInterval(timer);
      window.removeEventListener('resize', handleResize);
      
      [pieChartRef, lineChartRef, barChartRef].forEach(ref => {
        if (ref.current) {
          const chart = echarts.getInstanceByDom(ref.current);
          chart?.dispose();
        }
      });
    };
  }, []);

  // 格式化时间
  const formatTime = (date: Date) => {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
  };
  
  // 格式化日期
  const formatDate = (date: Date) => {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}/${month}/${day}`;
  };

  return (
    <>
      <DashboardContainer>
        <div>
          <Panel>
            <Header>商品品牌入驻情况</Header>
            <div style={{ display: "flex", justifyContent: "space-around" }}>
              <div style={{ textAlign: "center" }}>
                <CircleProgress color="#ff4bec" percentage={86}>
                  <div className="percentage">86%</div>
                </CircleProgress>
                <div>总入驻率</div>
              </div>
              <div style={{ textAlign: "center" }}>
                <CircleProgress color="#00f2f1" percentage={57}>
                  <div className="percentage">57%</div>
                </CircleProgress>
                <div>服务占比</div>
              </div>
              <div style={{ textAlign: "center" }}>
                <CircleProgress color="#0066ff" percentage={92}>
                  <div className="percentage">92%</div>
                </CircleProgress>
                <div>商品占比</div>
              </div>
            </div>
          </Panel>
          <Panel>
            <Header>本月销售排行</Header>
            <TableContainer>
              <table>
                <thead>
                  <tr>
                    <th>排名</th>
                    <th>商品品类</th>
                    <th>成交人数</th>
                    <th>销售金额</th>
                  </tr>
                </thead>
                <tbody>
                  {list.map((item, index) => (
                    <tr key={index}>
                      <td>{index + 1}</td>
                      <td>{item.name}</td>
                      <td>{item.buyers}人</td>
                      <td>{item.amount}元</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </TableContainer>
          </Panel>
          <Panel>
            <Header>线上下销售占比</Header>
            <div
              style={{
                display: "flex",
                justifyContent: "space-around",
                height: "220px",
              }}
            >
              <div style={{ textAlign: "center", height: "100%" }}>
                <SemiCircleProgress color="#00f2f1" percentage={69}>
                  <div className="percentage">69%</div>
                  <div className="label">线上销售</div>
                </SemiCircleProgress>
              </div>
              <div style={{ textAlign: "center" }}>
                <SemiCircleProgress color="#7a1dff" percentage={31}>
                  <div className="percentage">31%</div>
                  <div className="label">门店销售</div>
                </SemiCircleProgress>
              </div>
            </div>
          </Panel>
        </div>
        <div>
          <Panel>
            <Header>商品分类交易占比/近30天</Header>
            <ChartContainer ref={pieChartRef} />
          </Panel>
          <Panel>
            <Header>交易类型占比</Header>
            <ChartContainer ref={barChartRef} />
          </Panel>
        </div>
        <div>
          <Panel>
            <Header>本月前四门店销售情况</Header>
            <div
              style={{
                display: "flex",
                justifyContent: "space-around",
                marginBottom: "20px",
              }}
            >
              {[
                { value: "123万", label: "二号店" },
                { value: "98万", label: "一号店" },
                { value: "65万", label: "三号店" },
                { value: "39万", label: "四号店" },
              ].map((item, index) => (
                <div key={index} style={{ textAlign: "center" }}>
                  <div style={{ fontSize: "24px", color: "#00f2f1" }}>
                    {item.value}
                  </div>
                  <div>{item.label}</div>
                </div>
              ))}
            </div>
          </Panel>
          <Panel>
            <Header>近3日各时段访客量</Header>
            <ChartContainer ref={lineChartRef} />
          </Panel>
          <Panel>
            <Header>交易类型占比</Header>
            <div style={{ display: "flex", justifyContent: "space-around" }}>
              <div style={{ textAlign: "center" }}>
                <div
                  style={{
                    fontSize: "36px",
                    background: "linear-gradient(to bottom, #00f2f1, #0066ff)",
                    WebkitBackgroundClip: "text",
                    WebkitTextFillColor: "transparent",
                    fontWeight: "bold",
                  }}
                >
                  60%
                </div>
                <div>新拍商品占比</div>
              </div>
              <div style={{ textAlign: "center" }}>
                <div
                  style={{
                    fontSize: "36px",
                    background: "linear-gradient(to bottom, #ff4bec, #7a1dff)",
                    WebkitBackgroundClip: "text",
                    WebkitTextFillColor: "transparent",
                    fontWeight: "bold",
                  }}
                >
                  40%
                </div>
                <div>正价商品占比</div>
              </div>
            </div>
          </Panel>
        </div>
      </DashboardContainer>
    </>
  );
};

export default CityStores;